package com.moduleSys.web;

import com.moduleSys.entity.system.User;
import com.moduleSys.userService.UserService;
import com.moduleSys.utils.json.JsonResult;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;


/**
 * Created by czw on 2017/6/30 0030.
 */
@RestController
public class IndexController {

    private static final Logger logger = LoggerFactory.getLogger(IndexController.class);

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/admin/userLogin",method = {RequestMethod.GET,RequestMethod.POST})
    public String index(HttpServletRequest request){
        /**
         *  password 前端经过 md5 加密
         */
        String password = request.getParameter("password");
        String username = request.getParameter("username");
        User users = null;
        String msg = null;
        String reqMsg = null;
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password, false);
        if (!subject.isAuthenticated()) {
            try {
                token.setRememberMe(true);
                subject.login(token);
                users = (User) session.getAttribute("user");
            } catch (UnknownAccountException var12) {
                logger.info("账号不存在");
                reqMsg = new JsonResult(-1,"","账号不存在").toJsonString();
            } catch (IncorrectCredentialsException var13) {
                var13.printStackTrace();
                logger.info("密码错误");
                reqMsg = new JsonResult(0,"","密码错误").toJsonString();
            } catch ( LockedAccountException var14){
                var14.printStackTrace();
                logger.info("账号已被锁定12小时");
                reqMsg = new JsonResult(1,"","账号已被锁定12小时").toJsonString();
            }
        }
        if( users != null ){
            reqMsg = new JsonResult(2,"","登陆成功").toJsonString();
        }
        return reqMsg;
    }

    @RequestMapping(value = "/admin/main",method = {RequestMethod.GET,RequestMethod.POST})
    public ModelAndView admin(){
        return new ModelAndView("/backstage/index");
    }
}
